import * as echarts from 'echarts';
import { onMounted, onUnmounted, type Ref } from 'vue';
interface ChartHook {
  chart: echarts.ECharts | null;
  setChartOption: (newOptions: echarts.EChartsOption) => void;
}
/**
 * 抽离共性的图表逻辑 统一管理echarts的渲染和销毁逻辑
 * @param pieRef
 * @param pieDatas
 * @returns
 */
export default function useChart(
  pieRef: Ref<HTMLElement>,
  options: echarts.EChartsOption,
): ChartHook {
  // let chart: Ref<echarts.ECharts | null> = ref(null)
  let chart: echarts.ECharts | null = null

  onMounted(() => {
    if (pieRef.value) {
      chart = echarts.init(pieRef.value, undefined, { renderer: 'svg' })
      chart.setOption(options)
    }
  })

  onUnmounted(() => {
    chart?.dispose()
    chart = null
  })

  // 暴露一个方法用于重新设置选项 因为chart是一个常量，外部会丢失对chart的引用，而setChartOption是一个函数，他的引用不会丢失
  const setChartOption = (newOptions: echarts.EChartsOption) => {
    if (chart) {
      chart.setOption(newOptions)
    }
  }
  return {
    chart,
    setChartOption,
  }
}
